<?php

namespace App\Http\Controllers;

use App\Models\Ad;
use App\Models\Shop;
use App\Models\ShopFavorites;
use App\Models\Tuan;
use App\Models\TuanInfo;
use DB;
use Exception;
use Illuminate\Http\Request;

/**
 * 商铺相关
 */
class ShopController extends Controller
{
    /**
     * 口碑排行榜（5个）首页用
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function ranks_shop(Request $request)
    {
        try {
            $status = 0;
            $data   = [];
            $cityID = $request->get('city_id'); //城市id
            if (empty($cityID)) {
                throw new Exception('缺少参数！');
            }

            //口碑排行榜(先找广告表)
            $ads = Ad::where(['site_id' => 3, 'city_id' => $cityID, 'closed' => 1])
                ->where('bg_date', '<', time())->where('end_date', '>', time())
                ->orderBy('orderby')
                ->pluck('goal')
                ->toArray();

            $ids = Shop::where(['city_id' => $cityID, 'closed' => 1, 'audit' => 1])
                ->where('score_num', '>', 0)
                ->orderByRaw('score/score_num  desc')
                ->pluck('shop_id')->toArray();

            //合并数组并去重
            $shopIds = array_unique(array_merge($ads, $ids));
            $qs      = array_fill(0, count($shopIds), '?');

            $shops = Shop::whereIn('shop_id', $shopIds)
                ->orderByRaw(DB::raw("FIELD(shop_id," . implode(',', $qs) . ")"), $shopIds)->limit(5)->get();

            //处理数据
            $data = [];
            foreach ($shops as $key => $value) {
                $data[$key]['shop_id']   = $value->shop_id;
                $data[$key]['shop_name'] = $value->shop_name;
                $data[$key]['logo']      = $value->logo;
                $data[$key]['star']      = sprintf('%.1f', ($value->score / $value->score_num));
            }

            $status = 1;
            $msg    = '查询成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 商家详情
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function shop_info(Request $request)
    {
        try {
            $status  = 0;
            $data    = [];
            $shop_id = $request->get('shop_id');
            $user_id = $request->get('user_id') ?? 0;
            if (empty($shop_id)) {
                throw new Exception('缺少参数！');
            }
            $shop = Shop::where(['shop_id' => $shop_id])->first();
            if (!$shop) {
                throw new Exception('店铺不存在！');
            }
            //查找是否收藏
            $is_favority = 0;
            if ($user_id != 0) {
                $is_favority = ShopFavorites::where(['shop_id' => $shop_id, 'user_id' => $user_id])->value('closed');
            }
            //商铺信息
            $data['shop_id']       = $shop->shop_id;
            $data['shop_name']     = $shop->shop_name;
            $data['logo']          = $shop->logo;
            $data['addr']          = $shop->addr;
            $data['tel']           = $shop->tel;
            $data['business_date'] = $shop->business_date;
            $data['business_type'] = $shop->business_type;
            $data['business_time'] = $shop->business_time;
            $data['star']          = intval(($shop->score / $shop->score_num) * 10) / 10;
            $data['is_favority']   = $is_favority; //是否收藏
            $data['lng']           = $shop->lng; //地理经度
            $data['lat']           = $shop->lat; //地理纬度

            $status = 1;
            $msg    = "查询成功！";

        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 商铺优惠
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function shop_discounts(Request $request)
    {
        try {
            $status  = 0;
            $data    = [];
            $shop_id = $request->get('shop_id');
            if (empty($shop_id)) {
                throw new Exception('缺少参数！');
            }
            $shop = Shop::where(['shop_id' => $shop_id])->first();
            if (!$shop) {
                throw new Exception('店铺不存在！');
            }
            $tuans = Tuan::where(['shop_id' => $shop_id])->pluck('tuan_id');
            $infos = TuanInfo::where(['status' => 1, 'closed' => 1, 'audit' => 1])
                ->whereIn('tuan_id', $tuans)
                ->select('tuan_id', 'title', 'photo', 'tuan_price', 'photo_oss', 'end_date')
                ->get();

            //处理数据
            foreach ($infos as $key => $value) {
                $data[$key]['tuan_id']    = $value->tuan_id;
                $data[$key]['title']      = $value->title;
                $data[$key]['photo']      = $value->photo;
                $data[$key]['tuan_price'] = sprintf('%.2f', $value->tuan_price / 100);
                $data[$key]['end_date']   = date('Y-m-d', $value->end_date);

            }

            $status = 1;
            $msg    = "查询成功";
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 商家服务(商铺属性)
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function shop_attr_values(Request $request)
    {
        try {
            $status  = 0;
            $data    = [];
            $shop_id = $request->get('shop_id');
            if (empty($shop_id)) {
                throw new Exception('缺少参数！');
            }
            $shop = Shop::where(['shop_id' => $shop_id])->first();
            if (!$shop) {
                throw new Exception('店铺不存在！');
            }
            $attrs = $shop->shop_attr_value;
            //处理数据
            foreach ($attrs as $key => $value) {
                $data[$key]['front_style'] = $value->front_style;
                $data[$key]['icon']        = $value->icon;
            }
            $status = 1;
            $msg    = "查询成功";
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 商铺附近团购
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function shop_nearby_tuans(Request $request)
    {
        try {
            $status  = 0;
            $data    = [];
            $shop_id = $request->get('shop_id');
            if (empty($shop_id)) {
                throw new Exception('缺少参数！');
            }
            //查找商圈
            $business_id = Shop::where(['shop_id' => $shop_id])->value('business_id');
            $tuans       = TuanInfo::where([
                'business_id' => $business_id, 'status' => 1, 'closed' => 1, 'audit' => 1,
            ])->limit(4)->get();
            //处理数据
            foreach ($tuans as $key => $value) {
                $data[$key]['tuan_id']    = $value->tuan_id;
                $data[$key]['title']      = $value->title;
                $data[$key]['photo']      = $value->photo;
                $data[$key]['tuan_price'] = sprintf('%.2f', $value->tuan_price / 100);
                $data[$key]['industry']   = $value->tuan->industry->name;
            }

            $status = 1;
            $msg    = "查询成功";
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }
        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }
}
